const Person = require('../../../models/person');
import { NextApiRequest, NextApiResponse } from 'next';
import dbConnect from '../../../utils/helpers/dbHelpers';
import {
  IPerson,
  SPersonResponse,
} from '../../../utils/interface/personInterface';

async function handler(
  req: NextApiRequest,
  res: NextApiResponse<SPersonResponse>
) {
  const { method } = req;

  await dbConnect();

  switch (method) {
    case 'GET': {
      try {
        const dataId = req.query.dataId!.toString();

        const person: IPerson = await Person.findOne({ customID: dataId });

        if (!person) {
          throw new Error('Person with this id does not exist!');
        }

        res.status(200).json({
          message: 'Fetch single data successfull!',
          singleData: person,
        });
      } catch (error) {
        if (error instanceof Error)
          res.status(400).json({ message: error.message });
        else res.status(400).json({ message: 'Unexpected error' + error });
      }
      break;
    }
    default:
      res.status(405).json({ message: 'Method not allowed' });
      break;
  }
}

export default handler;
